package com.cms.util;

import java.math.BigDecimal;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.ExtendParams;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.cms.Config;

public class AlipayUtils {
    
      /** 异步地址 */
      public static String payNotifyUrl = "/common/pay_notify/alipayNotify";
    
          //网页支付
        public static void webPay(String out_trade_no,BigDecimal amount,String subject,String returnUrl,String params,HttpServletRequest httpRequest,HttpServletResponse httpResponse){
        	Config config = SystemUtils.getConfig();
        	try{
                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", config.getAlipay_appId(), config.getAlipay_appPrivateKey(), AlipayConstants.FORMAT_JSON, AlipayConstants.CHARSET_UTF8, config.getAlipay_publicKey(), AlipayConstants.SIGN_TYPE_RSA2); //获得初始化的AlipayClient
                AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
                alipayRequest.setReturnUrl(returnUrl);
                alipayRequest.setNotifyUrl(payNotifyUrl);//在公共参数中设置回跳和通知地址
                alipayRequest.setBizContent("{" +
                        "    \"out_trade_no\":\""+out_trade_no+"\"," +
                        "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                        "    \"total_amount\":"+amount.toString()+"," +
                        "    \"subject\":\""+subject+"\"," +
                        "    \"body\":\""+subject+"\"," +
                        "    \"passback_params\":\""+URLEncoder.encode(params,AlipayConstants.CHARSET_UTF8)+"\"," +    //URLEncoder.encode(orderId,"UTF-8")
                        "    \"extend_params\":{" +
                        "    \"sys_service_provider_id\":\""+config.getAlipay_appId()+"\"" +
                        "    }"+
                        "  }");//填充业务参数
                String form="";
                try {
                    form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
                } catch (AlipayApiException e) {
                    e.printStackTrace();
                }
                httpResponse.setContentType("text/html;charset=" + AlipayConstants.CHARSET_UTF8);
                httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
                httpResponse.getWriter().flush();
                httpResponse.getWriter().close();
            }catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    
        //app支付
        public static String appPay(String out_trade_no,BigDecimal amount,String subject,String params){
        	Config config = SystemUtils.getConfig();
        	try {
		            //实例化客户端
		            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", config.getAlipay_appId(), config.getAlipay_appPrivateKey(), AlipayConstants.FORMAT_JSON, AlipayConstants.CHARSET_UTF8, config.getAlipay_publicKey(), AlipayConstants.SIGN_TYPE_RSA2);
		            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		            //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		            model.setBody(subject);
		            model.setSubject(subject);
		            model.setOutTradeNo(out_trade_no);
		            model.setTimeoutExpress("30m");
		            model.setTotalAmount(amount.toString());
		            model.setProductCode("QUICK_MSECURITY_PAY");
		            model.setPassbackParams(URLEncoder.encode(params,AlipayConstants.CHARSET_UTF8));
		            ExtendParams extendParams = new ExtendParams(); //业务扩展参数，可选
		            extendParams.setSysServiceProviderId(config.getAlipay_appId());
		            model.setExtendParams(extendParams);
		            request.setBizModel(model);
		            request.setNotifyUrl(payNotifyUrl);
                    //这里和普通的接口调用不同，使用的是sdkExecute
                    AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                    System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
                    return response.getBody();
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
            }
        }
        
        //手机网页支付
        public static void wapPay(String out_trade_no,BigDecimal amount,String subject,String returnUrl,String params,HttpServletRequest httpRequest,HttpServletResponse httpResponse){
        	Config config = SystemUtils.getConfig();
        	try {
                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", config.getAlipay_appId(), config.getAlipay_appPrivateKey(), AlipayConstants.FORMAT_JSON, AlipayConstants.CHARSET_UTF8, config.getAlipay_publicKey(), AlipayConstants.SIGN_TYPE_RSA2); //获得初始化的AlipayClient
                AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
                alipayRequest.setReturnUrl(returnUrl);
                alipayRequest.setNotifyUrl(payNotifyUrl);//在公共参数中设置回跳和通知地址
                alipayRequest.setBizContent("{" +
                        "   \"out_trade_no\":\""+out_trade_no+"\"," +
                        "   \"product_code\":\"QUICK_WAP_PAY\"" +
                        "   \"total_amount\":\""+amount.toString()+"\"," +
                        "   \"subject\":\""+subject+"\"," +
                        "   \"body\":\""+subject+"\"," +
                        "   \"passback_params\":\""+URLEncoder.encode(params,AlipayConstants.CHARSET_UTF8)+"\"," +    //URLEncoder.encode(orderId,"UTF-8")
                        "   \"extend_params\":{" +
                        "   \"sys_service_provider_id\":\""+config.getAlipay_appId()+"\"" +
                        " }");//填充业务参数
                String form="";
                form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
                httpResponse.setContentType("text/html;charset=" + AlipayConstants.CHARSET_UTF8);
                httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
                httpResponse.getWriter().flush();
                httpResponse.getWriter().close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
}
